package com.jicheng.service.impl;

import com.jicheng.Utils.DESEncryptUtil;
import com.jicheng.Utils.ServerUtil;
import com.jicheng.dto.file.FileDataParams;
import com.jicheng.dto.file.FileParams;
import com.jicheng.dto.task.*;
import com.jicheng.entity.File;
import com.jicheng.entity.Task;
import com.jicheng.ext.dto.PagingResult;
import com.jicheng.ext.enums.ApiResponseCode;
import com.jicheng.ext.exceptions.BaseException;
import com.jicheng.ext.util.BeanConvertor;
import com.jicheng.ext.util.UUIDUtils;
import com.jicheng.mapper.FileMapper;
import com.jicheng.mapper.TaskAttachmentMapper;
import com.jicheng.mapper.TaskMapper;
import com.jicheng.mapper.template.TemplateMapMapper;
import com.jicheng.service.ITaskService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@Service
public class TaskServiceImpl implements ITaskService {

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private TemplateMapMapper templateMapMapper;
    @Autowired
    private TaskAttachmentMapper taskAttachmentMapper;


    @Override
    public PagingResult<TaskDto> getTaskList(PagingTaskParams params) {
        notNull("params", params);
        PagingResult<TaskDto> result = new PagingResult<>();
        List<Task> list = taskMapper.getList(params);
        if (CollectionUtils.isEmpty(list)) {
            return result;
        }
        long count = taskMapper.getCount(params);
        result.setTotal(count);
        result.setList(BeanConvertor.copy(list, TaskDto.class));
        return result;
    }

    @Override
    public void syncFormJob(FormTaskParams params) {
        notNull("params", params);

    }

    @Transactional
    @Override
    public void syncJobData(TaskDataParams params) {
        notNull("params", params);
        notNull("name", params.getName());
        notNull("type", params.getType());

        Task task = BeanConvertor.copy(params, Task.class);
        if (StringUtils.isEmpty(task.getId())) {
            task.setId(UUIDUtils.uuid());
            taskMapper.insertSelective(task);
        } else {
            taskMapper.updateByPrimaryKeySelective(task);
        }

    }

    @Transactional
    @Override
    public void syncFile(FileDataParams params) {
        notNull("params", params);
        List<FileParams> fileParamsList = params.getFileList();
        if (CollectionUtils.isEmpty(fileParamsList)) {
            throw new BaseException(ApiResponseCode.参数为空, " fileList is not null");
        }
        for (FileParams file : fileParamsList) {
            String taskId = file.getTaskId();
            notNull("taskId", taskId);
            File fileEntity = new File();
            fileEntity.setTaskId(taskId);
            List<MultipartFile> fileList = file.getFileList();
            for (MultipartFile multipartFile : fileList) {
                String name = multipartFile.getName();
                fileEntity.setName(name);
                //TODO 存储文件，返回文件路径
                fileEntity.setPath("");
                fileEntity.preCreate();
                fileMapper.insertSelective(fileEntity);
            }
        }
    }

    @Override
    public List<TemplateDto> getBusTemplateList(PagingTemplateParams params) {
        List<TemplateDto> busTemplateList = taskMapper.getBusTemplateList(params);

        return busTemplateList;
    }

    @Override
    public TaskDetailDto getTaskDetail(String taskId, HttpServletRequest request) {
        String serverIpPort = ServerUtil.getServerIPPort(request);
        TaskDetailDto taskDetailDto = taskMapper.getTaskDetail(taskId);
        List<TemplateFileDto> template = templateMapMapper.getTempDetail(taskId);
        for (TemplateFileDto templateFileDto : template) {
            if (templateFileDto.getFile() != null) {
//                templateFileDto.setFile(serverIpPort + "/file" + templateFileDto.getFile());
                java.io.File file = new java.io.File(templateFileDto.getFile().replace("\\", "/"));
                try {
                    //解密
                    String base64 = DESEncryptUtil.decryption("H:/key.k", templateFileDto.getFile().replace("\\", "/"), "decrypt");
//                    templateFileDto.setFile(serverIpPort + "/app-file/IoReadImage?decrypt=" + decrypt);
                    templateFileDto.setFile("data:image/jpg;base64,"+base64);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        List<AttachmentDto> attachment = taskAttachmentMapper.getTaskAttachDetail(taskId);
            List suffix = Arrays.asList(".doc",".docx",".xlsx",".xls",".pptx",".ppt",".txt") ;
        for (AttachmentDto attachmentDto : attachment) {
            if (attachmentDto.getFile() != null) {
//                attachmentDto.setFile(serverIpPort + "/file" + attachmentDto.getFile());
                try {
//                    byte[] decrypt = DESEncryptUtil.decryption2Byte("H:/key.k", "D:" + attachmentDto.getFile(), "decrypt");
                    String substring = attachmentDto.getFileName().substring(attachmentDto.getFileName().lastIndexOf("."));
                    if(suffix.contains(substring)){
                        attachmentDto.setFile(serverIpPort+"/app-file/getInputStream?path="+ attachmentDto.getFile());

                    }else {

                        attachmentDto.setFile(serverIpPort+"/app-file/getByte?path="+ attachmentDto.getFile());
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        taskDetailDto.setTemplate(template);
        taskDetailDto.setAttachment(attachment);
        return taskDetailDto;
    }

    @Override
    public TemplateFileDto getTemplateDetail(String id, HttpServletRequest request) {
        String serverIpPort = ServerUtil.getServerIPPort(request);
        TemplateFileDto templateDetail = templateMapMapper.getTemplateDetail(id);
        if (templateDetail.getFile() != null) {
            templateDetail.setFile(serverIpPort + "/file" + templateDetail.getFile());
        }
        return templateDetail;
    }

    @Override
    public List<String> getTaskType() {
        return taskMapper.getTaskType();
    }

    @Override
    public List<String> getTemplateType() {
        return taskMapper.getTemplateType();
    }


}
